package jfoo.playlist;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.AbstractListModel;

import jfoo.ControlCenter;


public class PlaylistListModel extends AbstractListModel implements
		MutableListModel, Runnable {

	private ArrayList<Playlist> playlists = null;
	private boolean loaded = false;
	private PlaylistList playlistList;

	public PlaylistListModel(ControlCenter controlCenter) {
		controlCenter.setPlaylistListModel(this);
		new Thread(this).start();
	}
	
	public void setVue(PlaylistList playlistList){
		this.playlistList = playlistList;
	}


	public boolean isCellEditable(int index) {
		return true;
	}
	
	public void handleCurrentPlaying(Playlist playlist, int currentlyPlayingIndex){
		
		for (Iterator<Playlist> iterator = playlists.iterator(); iterator.hasNext();) {
			Playlist p = iterator.next();
			if (p==playlist){
				p.setCurrentlyPlayingIndex(currentlyPlayingIndex);
			}else{
				p.setCurrentlyPlayingIndex(-1);
			}
		}
	}


	public void setValueAt(Object value, int index) {
		playlists.get(index).setName(value.toString());
	}

	public Object getElementAt(int index) {

		return playlists.get(index);

	}

	public int getSize() {
		if (playlists != null) {
			return playlists.size();
		} else {
			return 0;
		}
	}

	public void addPlaylist(Playlist playlist) {

		this.playlists.add(playlist);
		this.fireIntervalAdded(this, this.getSize(), this.getSize());

	}

	public int removePlaylist(int index) {

		this.playlists.remove(index);
		this.fireIntervalRemoved(this, index, index);
		return index;
	}

	public ArrayList<Playlist> getPlaylists() {
		return playlists;
	}

	public void setPlaylists(ArrayList<Playlist> playlists) {
		this.playlists = playlists;
	}

	@Override
	public void run() {
		File ft = new File("playlists.data");
		if (ft.exists()) {

			try {
				ObjectInputStream lecteur = new ObjectInputStream(
						new FileInputStream(ft));
				playlists = ((ArrayList<Playlist>) lecteur.readObject());

			} catch (java.io.InvalidClassException ex) {
				System.out.println("les playlists ne sont plus a jour");
				playlists = new ArrayList<Playlist>();
				playlists.add(new Playlist("New Playlist"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {

			playlists = new ArrayList<Playlist>();
			playlists.add(new Playlist("New Playlist"));
		}
		while(playlistList == null){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		playlistList.setPlaylist(0);
		

	}

}
